-
Notifications
You must be signed in to change notification settings - Fork 5
/
+page.server.ts
96 lines (77 loc) · 2.41 KB
/
+page.server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import type { Actions } from "./$types.js";
import type { Document } from "$lib/api/types";
import { fail, redirect } from "@sveltejs/kit";
import { CSRF_COOKIE_NAME } from "@/config/config.js";
import { destroy, edit, redact } from "$lib/api/documents";
import { isErrorCode } from "$lib/utils/api";
export function load({ cookies }) {
const csrf_token = cookies.get(CSRF_COOKIE_NAME);
return { csrf_token };
}
/**
* All document actions are defined here, because users end up
* back on the document viewer after any successful action.
*/
export const actions = {
async delete({ cookies, fetch, params }) {
const csrf_token = cookies.get(CSRF_COOKIE_NAME);
const { id } = params;
console.log(`Deleting document: ${id}`);
const resp = await destroy(id, csrf_token, fetch).catch((e) => {
console.error(e);
});
// probably the API is down
if (!resp) {
return fail(500, { error: "Something went wrong." });
}
// something else broke
if (isErrorCode(resp.status)) {
// {"error": "..."}
return fail(resp.status, await resp.json());
}
return redirect(302, "/app/");
},
async edit({ cookies, fetch, request, params }) {
const csrf_token = cookies.get(CSRF_COOKIE_NAME);
const form = await request.formData();
const { id } = params;
const update: Partial<Document> = {};
// set any fields that aren't blank
Array.from(form).reduce((m, [k, v]) => {
if (v) {
m[k] = v;
}
return m;
}, update);
try {
const document = await edit(id, update, csrf_token, fetch);
return {
success: true,
document,
};
} catch (error) {
return fail(400);
}
},
async redact({ cookies, fetch, request, params }) {
const csrf_token = cookies.get(CSRF_COOKIE_NAME);
const form = await request.formData();
const redactions = JSON.parse(form.get("redactions") as string);
const resp = await redact(params.id, redactions, csrf_token, fetch).catch(
console.error,
);
// probably the API is down
if (!resp) {
return fail(500, { error: "Something went wrong." });
}
// something else broke
if (isErrorCode(resp.status)) {
// {"error": "..."}
return fail(resp.status, await resp.json());
}
return {
success: true,
redactions: await resp.json(), // this should be the same as above
};
},
} satisfies Actions;